<?

class sign_up_action extends action_controller
{
	public function execute()
	{
		if ( session::user_id() ) response::redirect('/');
		helper_html::$meta['title'] = 'Signup';
	}

	public function execute_post()
	{
		$this->json = array();

		if ( !$_POST['email'] || !$_POST['password'] )
			return $this->json = array('error' => 'All fields are required');

		if ( $_POST['password'] != $_POST['password_confirm'] )
			return $this->json = array('error' => 'Passwords do not match');
		
		if ( !strpos($_POST['email'], '@') )
			return $this->json = array('error' => 'Email is not valid');

		if ( user_peer::get_by('email', $_POST['email']) )
			return $this->json = array('error' => 'This email is already registered');

		if ( session::get('captcha') && ($_POST['captcha'] != session::get('captcha')) )
			return $this->json = array('error' => 'Security code is wrong');

		$data = array(
			'email' => $_POST['email'],
			'password' => md5($_POST['password']),
		);

		$id = user_peer::insert($data);

		$d = base64_encode($id . ';' . md5($id . $data['email'] . $data['password'] . 'activation'));
		$activation_url = 'http://' . $_SERVER['SERVER_NAME'] . '/sign/activate?d=' . $d;
		$body = 'Greetings!' . "\n" .
				'Please visit the link below to activate your account:' . "\n" .
				$activation_url . "\n\n" .
				config::get('email_signature');
		$m = new mail($data['email'], 'Email activation', $body);
		$m->send();
	}
}